/**
 * HTML生成器模块
 * 负责将页面数据转换为HTML预览页面
 */
class HtmlGenerator {
    constructor() {
        this.defaultStyles = this.getDefaultStyles();
    }

    /**
     * 获取默认样式
     * @returns {Object} 默认样式对象
     */
    getDefaultStyles() {
        return {
            pageContainer: {
                position: 'relative',
                width: '375px',
                minHeight: '667px',
                boxShadow: '0 0 20px rgba(0,0,0,0.1)'
            },
            element: {
                position: 'absolute',
                boxSizing: 'border-box'
            },
            body: {
                margin: '0',
                padding: '0',
                background: '#f5f5f5',
                minHeight: '100vh',
                position: 'relative',
                fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
                display: 'flex',
                justifyContent: 'center',
                alignItems: 'flex-start'
            }
        };
    }

    /**
     * 生成完整的HTML页面
     * @param {Object} pageData - 页面数据
     * @returns {string} HTML字符串
     */
    generateHTML(pageData) {
        // 检查是否是多页面数据
        if (pageData.pages && Array.isArray(pageData.pages)) {
            return this.generateMultiPageHTML(pageData);
        } else {
            // 单页面数据（兼容旧版本）
            const { background, elements } = pageData;
            
            const elementsHTML = this.generateElementsHTML(elements);
            const backgroundStyle = this.generateBackgroundStyle(background);
            const pageContainerStyle = this.generatePageContainerStyle(background);
            
            return this.generateCompleteHTML({
                elementsHTML,
                backgroundStyle,
                pageContainerStyle
            });
        }
    }

    /**
     * 生成多页面HTML
     * @param {Object} pageData - 多页面数据
     * @returns {string} HTML字符串
     */
    generateMultiPageHTML(pageData) {
        const { pages, pageSettings, currentPageIndex } = pageData;
        
        // 生成所有页面的HTML
        const pagesHTML = pages.map((page, index) => {
            // 确保elements是数组
            const elements = Array.isArray(page.elements) ? page.elements : [];
            const elementsHTML = this.generateElementsHTML(elements);
            const backgroundStyle = this.generateBackgroundStyle(page.background);
            
            // 为每个页面生成独立的容器样式
            const pageStyle = `
                position: relative;
                width: 375px;
                min-height: 667px;
                margin: 0 auto;
                ${backgroundStyle}
            `;
            
            return `
                <div class="swiper-slide page" id="page-${index}" style="${pageStyle}">
                    ${elementsHTML}
                </div>
            `;
        }).join('\n');

        // 生成翻页控制HTML
        const navigationHTML = this.generatePageNavigationHTML(pages.length, pageSettings);
        
        // 生成翻页样式
        const pageStyles = this.generateMultiPageStyles(pageSettings);
        
        return this.generateCompleteMultiPageHTML({
            pagesHTML,
            navigationHTML,
            pageStyles,
            pageSettings,
            currentPageIndex,
            totalPages: pages.length
        });
    }

    /**
     * 生成页面导航HTML
     * @param {number} totalPages - 总页数
     * @param {Object} pageSettings - 页面设置
     * @returns {string} 导航HTML字符串
     */
    generatePageNavigationHTML(totalPages, pageSettings) {
        if (totalPages <= 1) return '';
        
        const { pageSwitchMode } = pageSettings;
        const showNavigation = pageSwitchMode === 'click' || pageSwitchMode === 'both';
        
        if (!showNavigation) return '';
        
        return `
            <div class="page-navigation">
                <button id="prevPage" class="nav-btn">← 上一页</button>
                <span id="pageIndicator">1 / ${totalPages}</span>
                <button id="nextPage" class="nav-btn">下一页 →</button>
            </div>
        `;
    }

    /**
     * 生成多页面样式
     * @param {Object} pageSettings - 页面设置
     * @returns {string} CSS样式字符串
     */
    generateMultiPageStyles(pageSettings) {
        const { transitionEffect, infiniteScroll } = pageSettings;
        
        return `
            <style>
                /* 全局样式重置 */
                * {
                    margin: 0;
                    padding: 0;
                    box-sizing: border-box;
                }
                
                html {
                    font-size: 16px;
                }
                
                body {
                    margin: 0;
                    padding: 0;
                    background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
                    min-height: 100vh;
                    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
                    display: grid;
                    grid-template-columns: 1fr 1fr 1fr;
                    gap: 30px;
                    padding: 20px;
                    color: #333;
                }
                
                /* 移动端样式 - 优化三列布局显示 */
                @media (max-width: 768px) {
                    body {
                        background: #000;
                        padding: 0;
                        margin: 0;
                        display: block;
                        overflow: hidden;
                        height: 100vh;
                    }
                    
                    .left-section,
                    .middle-section,
                    .right-section {
                        display: none;
                    }
                    
                    /* 移动端专用页面容器 */
                    .mobile-page-container {
                        display: block !important;
                        position: fixed;
                        top: 0;
                        left: 0;
                        width: 100vw;
                        height: 100vh;
                        background: #000;
                        z-index: 9999;
                        overflow: hidden;
                    }
                    
                    .mobile-page-container .page {
                        position: absolute !important;
                        top: 0;
                        left: 0;
                        width: 100vw;
                        height: 100vh;
                        background: #fff;
                    }
                    
                    /* 移动端页面切换优化 - 上下滑动 */
                    .mobile-page-container {
                        touch-action: pan-y;
                    }
                    
                    .mobile-page-container .page {
                        transition: transform 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94);
                    }
                }
                
                /* 移动端预览专用样式 */
                body.mobile-preview {
                    background: #000;
                    padding: 0;
                    margin: 0;
                    display: block;
                    overflow: hidden;
                    height: 100vh;
                }
                
                body.mobile-preview .left-section {
                    display: none;
                }
                
                body.mobile-preview .right-section {
                    display: none;
                }
                
                body.mobile-preview .phone-nav-buttons {
                    display: none;
                }
                
                /* 移动端直接显示页面容器 */
                body.mobile-preview .page-container {
                    position: fixed;
                    top: 0;
                    left: 0;
                    width: 100vw;
                    height: 100vh;
                    background: #000;
                    z-index: 1;
                }
                
                body.mobile-preview .page {
                    width: 100vw;
                    height: 100vh;
                    background: #fff;
                }
                
                /* 移动端页面切换优化 - 上下滑动 */
                body.mobile-preview .page-container {
                    touch-action: pan-y;
                }
                
                body.mobile-preview .page {
                    transition: transform 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94);
                }
                
                /* 移动端专用页面容器 */
                .mobile-page-container {
                    display: none;
                    position: fixed;
                    top: 0;
                    left: 0;
                    width: 100vw;
                    height: 100vh;
                    background: #000;
                    z-index: 9999;
                    overflow: hidden;
                }
                
                .mobile-page-container .page {
                    position: absolute !important;
                    top: 0;
                    left: 0;
                    width: 100vw;
                    height: 100vh;
                    background: #fff;
                }
                
                /* 移动端页面切换指示器 */
                .mobile-page-indicator {
                    position: fixed;
                    top: 20px;
                    left: 50%;
                    transform: translateX(-50%);
                    background: rgba(0, 0, 0, 0.7);
                    color: white;
                    padding: 8px 16px;
                    border-radius: 20px;
                    font-size: 14px;
                    font-weight: 600;
                    z-index: 10000;
                    backdrop-filter: blur(10px);
                }
                
                @media (max-width: 768px) {
                    .mobile-page-container {
                        display: block;
                    }
                    
                    .left-section,
                    .right-section {
                        display: none;
                    }
                }
                
                body.mobile-preview .mobile-page-container {
                    display: block;
                }
                
                body.mobile-preview .left-section,
                body.mobile-preview .right-section {
                    display: none;
                }
                
                /* 第一列：预览信息和翻页按钮 */
                .left-section {
                    display: flex;
                    flex-direction: column;
                    align-items: center;
                    justify-content: flex-start;
                    gap: 20px;
                }
                
                /* 翻页按钮区域 - 放在H5预览下方 */
                .phone-nav-buttons {
                    display: flex;
                    flex-direction: row;
                    gap: 20px;
                    justify-content: center;
                    align-items: center;
                }
                
                /* 手机预览信息区域 */
                .phone-preview-info {
                    background: rgba(255, 255, 255, 0.95);
                    backdrop-filter: blur(10px);
                    border-radius: 16px;
                    padding: 20px;
                    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
                    border: 1px solid rgba(255, 255, 255, 0.3);
                    text-align: center;
                    width: 100%;
                    max-width: 375px;
                }
                
                .phone-preview-title {
                    font-size: 18px;
                    font-weight: 700;
                    color: #2d3748;
                    margin-bottom: 8px;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    gap: 8px;
                }
                
                .phone-preview-subtitle {
                    font-size: 14px;
                    color: #718096;
                    margin-bottom: 16px;
                }
                
                .phone-page-indicator {
                    background: linear-gradient(135deg, #667eea, #764ba2);
                    color: white;
                    padding: 8px 16px;
                    border-radius: 20px;
                    display: inline-block;
                    font-size: 14px;
                    font-weight: 600;
                    box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
                }
                
                .phone-nav-btn {
                    display: flex;
                    flex-direction: row;
                    align-items: center;
                    gap: 8px;
                    background: linear-gradient(135deg, #667eea, #764ba2);
                    color: white;
                    border: none;
                    padding: 12px 24px;
                    border-radius: 12px;
                    cursor: pointer;
                    font-size: 14px;
                    font-weight: 500;
                    transition: all 0.3s ease;
                    box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
                    min-width: 120px;
                    position: relative;
                    overflow: hidden;
                    border: 1px solid rgba(255,255,255,0.2);
                }
                
                .phone-nav-btn::before {
                    content: '';
                    position: absolute;
                    top: 0;
                    left: -100%;
                    width: 100%;
                    height: 100%;
                    background: linear-gradient(90deg, transparent, rgba(255,255,255,0.2), transparent);
                    transition: left 0.5s;
                }
                
                .phone-nav-btn:hover:not(:disabled)::before {
                    left: 100%;
                }
                
                .phone-nav-btn:hover:not(:disabled) {
                    background: linear-gradient(135deg, #5a67d8, #6b46c1);
                    transform: translateY(-2px);
                    box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
                }
                
                .phone-nav-btn:active:not(:disabled) {
                    transform: translateY(0);
                }
                
                .phone-nav-btn:disabled {
                    background: #94a3b8;
                    cursor: not-allowed;
                    opacity: 0.6;
                    transform: none;
                    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
                }
                
                .phone-prev-btn {
                    order: 1;
                }
                
                .phone-next-btn {
                    order: 2;
                }
                
                .btn-icon {
                    font-size: 16px;
                    font-weight: bold;
                }
                
                .btn-text {
                    font-size: 14px;
                    white-space: nowrap;
                    font-weight: 500;
                }
                
                .phone-frame {
                    width: 391px;  /* 375px + 16px padding */
                    height: 683px; /* 667px + 16px padding */
                    background: linear-gradient(145deg, #2d3748, #1a202c);
                    border-radius: 40px;
                    padding: 8px;
                    box-shadow: 0 20px 40px rgba(0,0,0,0.3), 
                                0 0 0 1px rgba(255,255,255,0.1);
                    position: relative;
                    border: 2px solid rgba(255,255,255,0.1);
                }
                
                .phone-frame::before {
                    content: '';
                    position: absolute;
                    top: 20px;
                    left: 50%;
                    transform: translateX(-50%);
                    width: 60px;
                    height: 4px;
                    background: #333;
                    border-radius: 2px;
                }
                
                .phone-screen {
                    width: 100%;
                    height: 100%;
                    background: #fff;
                    border-radius: 32px;
                    overflow: hidden;
                    position: relative;
                }
                
                /* Swiper容器样式 */
                .previewSwiper {
                    width: 100%;
                    height: 100%;
                }
                
                .mobileSwiper {
                    width: 100vw;
                    height: 100vh;
                }
                
                .mobileSwiper .swiper-slide {
                    width: 100vw;
                    height: 100vh;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    padding: 20px;
                    box-sizing: border-box;
                }
                
                .mobileSwiper .page {
                    width: 375px;
                    min-height: 667px;
                    position: relative;
                    overflow: hidden;
                    background: #fff;
                    border-radius: 20px;
                }
                
                .page.active {
                    z-index: 2;
                }
                
                .page.prev {
                    z-index: 1;
                }
                
                .page.next {
                    z-index: 1;
                }
                
                /* 确保第一个页面默认显示 */
                .page:first-child {
                    z-index: 2;
                }
                
                /* 移动端样式 - Swiper会处理定位 */
                @media (max-width: 768px) {
                    .page {
                        width: 100vw;
                        height: 100vh;
                    }
                }
                
                /* Swiper会处理所有的过渡效果，移除旧的CSS */
                
                /* 第二列和第三列信息区域 */
                .right-section {
                    display: flex;
                    flex-direction: column;
                    gap: 20px;
                }
                
                /* 第二列：手机预览框 */
                .middle-section {
                    display: flex;
                    flex-direction: column;
                    align-items: center;
                    justify-content: flex-start;
                }
                
                .phone-info {
                    text-align: center;
                    color: #666;
                }
                
                .phone-info h3 {
                    margin: 0 0 10px 0;
                    font-size: 24px;
                    font-weight: 600;
                    color: #333;
                }
                
                .phone-info p {
                    margin: 0 0 15px 0;
                    font-size: 16px;
                    color: #666;
                }
                
                .page-indicator {
                    background: #f1f5f9;
                    padding: 10px 20px;
                    border-radius: 25px;
                    display: inline-block;
                    border: 1px solid #e2e8f0;
                }
                
                .page-indicator span {
                    font-weight: 500;
                    font-size: 14px;
                    color: #475569;
                }
                
                .info-card {
                    background: white;
                    padding: 20px;
                    border-radius: 12px;
                    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
                    border: 1px solid #e2e8f0;
                }
                
                .info-card h4 {
                    margin: 0 0 12px 0;
                    color: #1e293b;
                    font-size: 16px;
                    font-weight: 600;
                }
                
                .info-card p {
                    margin: 0 0 8px 0;
                    color: #64748b;
                    font-size: 14px;
                    line-height: 1.5;
                }
                
                .info-card p:last-child {
                    margin-bottom: 0;
                }
                
                .setting-item {
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    padding: 8px 0;
                    border-bottom: 1px solid #f1f5f9;
                }
                
                .setting-item:last-child {
                    border-bottom: none;
                }
                
                .setting-item .label {
                    color: #64748b;
                    font-size: 14px;
                }
                
                .setting-item .value {
                    color: #1e293b;
                    font-size: 14px;
                    font-weight: 500;
                }
                
                .controls {
                    background: white;
                    padding: 20px;
                    border-radius: 12px;
                    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
                    border: 1px solid #e2e8f0;
                }
                
                .page-navigation {
                    display: flex;
                    align-items: center;
                    gap: 15px;
                    justify-content: center;
                }
                
                .nav-btn {
                    background: #3b82f6;
                    color: white;
                    border: none;
                    padding: 12px 24px;
                    border-radius: 8px;
                    cursor: pointer;
                    font-size: 14px;
                    font-weight: 500;
                    transition: all 0.2s;
                    min-width: 100px;
                    box-shadow: 0 2px 4px rgba(59, 130, 246, 0.2);
                }
                
                .nav-btn:hover:not(:disabled) {
                    background: #2563eb;
                    transform: translateY(-1px);
                    box-shadow: 0 4px 8px rgba(59, 130, 246, 0.3);
                }
                
                .nav-btn:disabled {
                    background: #94a3b8;
                    cursor: not-allowed;
                    opacity: 0.6;
                    transform: none;
                    box-shadow: none;
                }
                
                #pageIndicator {
                    font-size: 16px;
                    font-weight: 600;
                    min-width: 100px;
                    text-align: center;
                    color: #1e293b;
                    background: #f1f5f9;
                    padding: 12px 20px;
                    border-radius: 8px;
                    border: 1px solid #e2e8f0;
                }
                
                /* 触摸滑动支持 */
                .page-container.touch-enabled {
                    touch-action: pan-y;
                }
            </style>
        `;
    }

    /**
     * 生成完整的多页面HTML
     * @param {Object} data - 包含页面HTML、导航、样式等的数据
     * @returns {string} 完整的HTML字符串
     */
    generateCompleteMultiPageHTML(data) {
        const { pagesHTML, navigationHTML, pageStyles, pageSettings, currentPageIndex, totalPages } = data;
        
        return `<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>H5页面预览</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.css">
    ${pageStyles}
</head>
<body>
    <!-- 第一列：预览信息和翻页按钮 -->
    <div class="left-section">
        <!-- 预览信息区域 -->
        <div class="phone-preview-info">
            <div class="phone-preview-title">
                <span>📱</span>
                <span>H5页面预览</span>
            </div>
            <div class="phone-preview-subtitle">多页面H5活动页面实时预览</div>
            <div class="phone-page-indicator">
                <span id="currentPageInfo">页面 ${(currentPageIndex || 0) + 1} / ${totalPages}</span>
            </div>
        </div>
        
        <!-- 翻页按钮区域 -->
        <div class="phone-nav-buttons">
            <button id="phonePrevBtn" class="phone-nav-btn phone-prev-btn" disabled>
                <span class="btn-icon">←</span>
                <span class="btn-text">上一页</span>
            </button>
            <button id="phoneNextBtn" class="phone-nav-btn phone-next-btn">
                <span class="btn-text">下一页</span>
                <span class="btn-icon">→</span>
            </button>
        </div>
    </div>
    
    <!-- 第二列：手机预览框 -->
    <div class="middle-section">
        <!-- 手机模拟器 -->
        <div class="phone-frame">
            <div class="phone-screen">
                <div class="swiper previewSwiper">
                    <div class="swiper-wrapper">
                        ${pagesHTML}
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 第三列：页面设置、统计和操作说明 -->
    <div class="right-section">
        <div class="info-card">
            <h4>🎨 页面设置</h4>
            <div class="setting-item">
                <span class="label">翻页效果:</span>
                <span class="value">${pageSettings.transitionEffect === 'slide' ? '滑动' : pageSettings.transitionEffect === 'fade' ? '淡入淡出' : '无'}</span>
            </div>
            <div class="setting-item">
                <span class="label">无限翻页:</span>
                <span class="value">${pageSettings.infiniteScroll ? '是' : '否'}</span>
            </div>
            <div class="setting-item">
                <span class="label">切换方式:</span>
                <span class="value">${pageSettings.pageSwitchMode === 'click' ? '点击' : pageSettings.pageSwitchMode === 'swipe' ? '滑动' : '点击+滑动'}</span>
            </div>
        </div>
        
        <div class="info-card">
            <h4>📊 页面统计</h4>
            <div class="setting-item">
                <span class="label">总页数:</span>
                <span class="value">${totalPages} 页</span>
            </div>
           
            <div class="setting-item">
                <span class="label">生成时间:</span>
                <span class="value">${new Date().toLocaleString('zh-CN')}</span>
            </div>
        </div>
        
        <div class="info-card">
            <h4>🎮 操作说明</h4>
            <p>• 使用下方按钮进行页面切换</p>
            <p>• 在手机上可以滑动切换页面</p>
            <p>• 支持多种翻页效果和切换方式</p>
            <p>• 左侧区域集中了预览和切换功能</p>
        </div>
        
       
    </div>
    
    <!-- 移动端专用页面容器 -->
    <div class="mobile-page-container">
        <div class="mobile-page-indicator">
            <span id="mobilePageIndicator">页面 1 / ${totalPages}</span>
        </div>
        <div class="swiper mobileSwiper">
            <div class="swiper-wrapper">
                ${pagesHTML}
            </div>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.js"></script>
    <script>
        // 使用Swiper的多页面管理
        class MultiPageManager {
            constructor() {
                this.currentPage = 0;  // 预览页始终从第一页开始
                this.totalPages = ${totalPages};
                this.pageSettings = ${JSON.stringify(pageSettings)};
                this.isMobile = this.detectMobile();
                this.previewSwiper = null;
                this.mobileSwiper = null;
                console.log('MultiPageManager initialized with Swiper:', {
                    currentPage: this.currentPage,
                    totalPages: this.totalPages,
                    pageSettings: this.pageSettings,
                    isMobile: this.isMobile
                });
                this.init();
            }
            
            detectMobile() {
                return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) || 
                       window.innerWidth <= 768;
            }
            
            init() {
                // 移动端优化
                if (this.isMobile) {
                    this.setupMobileOptimization();
                    this.initMobileSwiper();
                } else {
                    this.initPreviewSwiper();
                }
                
                this.setupEventListeners();
                
                // 初始化页面指示器和按钮状态
                this.updatePageIndicators();
            }
            
            initPreviewSwiper() {
                const self = this;
                const swiperEl = document.querySelector('.previewSwiper');
                console.log('Looking for .previewSwiper:', swiperEl);
                
                if (!swiperEl) {
                    console.error('Preview Swiper element not found!');
                    return;
                }
                
                this.previewSwiper = new Swiper('.previewSwiper', {
                    direction: 'vertical',
                    allowTouchMove: this.pageSettings.pageSwitchMode === 'swipe' || this.pageSettings.pageSwitchMode === 'both',
                    loop: this.pageSettings.infiniteScroll || false,
                    speed: 600,
                    effect: this.pageSettings.transitionEffect === 'fade' ? 'fade' : 'slide',
                    initialSlide: 0,  // 始终从第一页开始
                    on: {
                        slideChange: function() {
                            console.log('Swiper slideChange:', this.realIndex);
                            self.currentPage = this.realIndex;
                            self.updatePageIndicators();
                            // 重新触发当前页面的动画
                            self.triggerPageAnimations(this.realIndex);
                        }
                    }
                });
                
                console.log('Preview Swiper initialized:', {
                    instance: this.previewSwiper,
                    slides: this.previewSwiper.slides ? this.previewSwiper.slides.length : 0,
                    activeIndex: this.previewSwiper.activeIndex,
                    allowTouchMove: this.previewSwiper.allowTouchMove
                });
                
                // 预览页始终从第一页开始，不需要跳转
            }
            
            initMobileSwiper() {
                const self = this;
                this.mobileSwiper = new Swiper('.mobileSwiper', {
                    direction: 'vertical',
                    allowTouchMove: true,
                    loop: this.pageSettings.infiniteScroll || false,
                    speed: 600,
                    effect: this.pageSettings.transitionEffect === 'fade' ? 'fade' : 'slide',
                    initialSlide: 0,  // 始终从第一页开始
                    on: {
                        slideChange: function() {
                            self.currentPage = this.realIndex;
                            self.updatePageIndicators();
                            // 重新触发当前页面的动画
                            self.triggerPageAnimations(this.realIndex);
                        }
                    }
                });
                
                // 预览页始终从第一页开始，不需要跳转
                console.log('Mobile Swiper initialized, initialSlide: 0');
            }
            
            setupMobileOptimization() {
                console.log('Setting up mobile optimization...');
                
                // 隐藏PC端布局
                const leftSection = document.querySelector('.left-section');
                const rightSection = document.querySelector('.right-section');
                if (leftSection) {
                    leftSection.style.display = 'none';
                }
                if (rightSection) {
                    rightSection.style.display = 'none';
                }
                
                // 显示移动端页面容器
                const mobilePageContainer = document.querySelector('.mobile-page-container');
                if (mobilePageContainer) {
                    mobilePageContainer.style.display = 'block';
                    console.log('Mobile page container displayed');
                } else {
                    console.error('Mobile page container not found');
                }
                
                // 强制启用滑动模式
                this.pageSettings.pageSwitchMode = 'swipe';
                
                // 添加移动端专用样式
                document.body.classList.add('mobile-preview');
                
                // Swiper会自动处理页面显示，不需要手动调用showPage
            }
            
            setupEventListeners() {
                // 手机翻页按钮
                const phonePrevBtn = document.getElementById('phonePrevBtn');
                const phoneNextBtn = document.getElementById('phoneNextBtn');
                
                if (phonePrevBtn) {
                    phonePrevBtn.addEventListener('click', () => this.prevPage());
                }
                
                if (phoneNextBtn) {
                    phoneNextBtn.addEventListener('click', () => this.nextPage());
                }
            }
            
            prevPage() {
                console.log('prevPage called', {
                    isMobile: this.isMobile,
                    mobileSwiper: this.mobileSwiper,
                    previewSwiper: this.previewSwiper,
                    currentPage: this.currentPage
                });
                
                if (this.isMobile && this.mobileSwiper) {
                    this.mobileSwiper.slidePrev();
                } else if (this.previewSwiper) {
                    this.previewSwiper.slidePrev();
                } else {
                    console.error('No swiper instance available!');
                }
            }
            
            nextPage() {
                console.log('nextPage called', {
                    isMobile: this.isMobile,
                    mobileSwiper: this.mobileSwiper,
                    previewSwiper: this.previewSwiper,
                    currentPage: this.currentPage
                });
                
                if (this.isMobile && this.mobileSwiper) {
                    this.mobileSwiper.slideNext();
                } else if (this.previewSwiper) {
                    this.previewSwiper.slideNext();
                } else {
                    console.error('No swiper instance available!');
                }
            }
            
            updatePageIndicators() {
                const pageInfo = document.getElementById('currentPageInfo');
                const mobileIndicator = document.getElementById('mobilePageIndicator');
                const phonePrevBtn = document.getElementById('phonePrevBtn');
                const phoneNextBtn = document.getElementById('phoneNextBtn');
                
                // 更新页面指示器
                if (pageInfo) {
                    pageInfo.textContent = \`页面 \${this.currentPage + 1} / \${this.totalPages}\`;
                }
                
                if (mobileIndicator) {
                    mobileIndicator.textContent = \`页面 \${this.currentPage + 1} / \${this.totalPages}\`;
                }
                
                // 更新按钮状态
                if (phonePrevBtn) {
                    phonePrevBtn.disabled = this.currentPage === 0 && !this.pageSettings.infiniteScroll;
                }
                
                if (phoneNextBtn) {
                    phoneNextBtn.disabled = this.currentPage === this.totalPages - 1 && !this.pageSettings.infiniteScroll;
                }
            }
            
            /**
             * 触发页面动画
             * @param {number} pageIndex - 页面索引
             */
            triggerPageAnimations(pageIndex) {
                console.log('预览页触发页面动画:', pageIndex);
                
                // 获取当前页面的所有元素
                const currentSlide = this.isMobile ? 
                    document.querySelector(\`.mobileSwiper .swiper-slide:nth-child(\${pageIndex + 1})\`) :
                    document.querySelector(\`.previewSwiper .swiper-slide:nth-child(\${pageIndex + 1})\`);
                
                if (!currentSlide) {
                    console.warn('Current slide not found for animation trigger:', pageIndex);
                    return;
                }
                
                console.log('找到当前slide:', currentSlide);
                
                // 查找所有元素（不限于已有动画类的元素）
                const allElements = currentSlide.querySelectorAll('.element');
                console.log('找到元素数量:', allElements.length);
                
                allElements.forEach((element, index) => {
                    console.log(\`处理元素 \${index + 1}:\`, element);
                    
                    // 检查元素是否有动画相关的样式
                    const hasAnimation = element.style.animationName && 
                                       element.style.animationName !== 'none' && 
                                       element.style.animationName !== '';
                    
                    if (!hasAnimation) {
                        console.log('元素没有动画样式，跳过');
                        return;
                    }
                    
                    console.log('元素有动画样式:', element.style.animationName);
                    
                    // 移除现有的动画类
                    const classesToRemove = Array.from(element.classList).filter(cls => 
                        cls.startsWith('animate__') || cls.startsWith('animate-')
                    );
                    console.log('要移除的动画类:', classesToRemove);
                    classesToRemove.forEach(cls => element.classList.remove(cls));
                    
                    // 使用 requestAnimationFrame 确保DOM更新后再添加动画
                    requestAnimationFrame(() => {
                        // 重新添加动画类
                        classesToRemove.forEach(cls => element.classList.add(cls));
                        console.log(\`重新触发元素 \${index + 1} 的动画\`);
                    });
                });
            }
            
            setupTouchEvents() {
                // 移动端使用专用容器，PC端使用普通容器
                const pageContainer = this.isMobile ? 
                    document.querySelector('.mobile-page-container') : 
                    document.querySelector('.page-container');
                
                console.log('Setting up touch events...');
                console.log('Is mobile:', this.isMobile);
                console.log('Page container:', pageContainer);
                
                if (!pageContainer) {
                    console.error('Page container not found!');
                    return;
                }
                
                let startX = 0;
                let startY = 0;
                let currentY = 0;
                let isDragging = false;
                let startTime = 0;
                
                pageContainer.addEventListener('touchstart', (e) => {
                    console.log('Touch start detected');
                    startX = e.touches[0].clientX;
                    startY = e.touches[0].clientY;
                    startTime = Date.now();
                    isDragging = false;
                });
                
                pageContainer.addEventListener('touchmove', (e) => {
                    if (!startX || !startY) return;
                    
                    currentY = e.touches[0].clientY;
                    const diffX = startX - e.touches[0].clientX;
                    const diffY = startY - currentY;
                    
                    // 移动端使用上下滑动，PC端使用左右滑动
                    const isVerticalSwipe = this.isMobile ? 
                        (Math.abs(diffY) > Math.abs(diffX) && Math.abs(diffY) > 10) :
                        (Math.abs(diffX) > Math.abs(diffY) && Math.abs(diffX) > 10);
                    
                    if (isVerticalSwipe) {
                        isDragging = true;
                        e.preventDefault();
                        
                        // 添加滑动时的实时效果
                        pageContainer.classList.add('swiping');
                        
                        // 实时更新页面位置
                        const allPages = document.querySelectorAll('.page');
                        allPages.forEach((page, index) => {
                            if (index === this.currentPage) {
                                const progress = Math.min(Math.abs(diffY) / 200, 1);
                                if (this.isMobile) {
                                    // 移动端上下滑动
                                    page.style.transform = 'translateY(' + (diffY * 0.3) + 'px)';
                                } else {
                                    // PC端左右滑动
                                    page.style.transform = 'translateX(' + (diffX * 0.3) + 'px)';
                                }
                                page.style.opacity = 1 - progress * 0.3;
                            }
                        });
                    }
                });
                
                pageContainer.addEventListener('touchend', (e) => {
                    console.log('Touch end detected, isDragging:', isDragging);
                    if (!isDragging) {
                        pageContainer.classList.remove('swiping');
                        return;
                    }
                    
                    const diffX = startX - e.changedTouches[0].clientX;
                    const diffY = startY - e.changedTouches[0].clientY;
                    const diffTime = Date.now() - startTime;
                    const velocity = this.isMobile ? Math.abs(diffY) / diffTime : Math.abs(diffX) / diffTime;
                    
                    // 移动端使用更低的阈值，更容易触发翻页
                    const threshold = this.isMobile ? (velocity > 0.3 ? 20 : 50) : (velocity > 0.5 ? 30 : 80);
                    
                    // 重置所有页面的transform
                    const allPages = document.querySelectorAll('.page');
                    allPages.forEach(page => {
                        page.style.transform = '';
                        page.style.opacity = '';
                    });
                    
                    const diff = this.isMobile ? diffY : diffX;
                    if (Math.abs(diff) > threshold) {
                        if (this.isMobile) {
                            // 移动端：向上滑动下一页，向下滑动上一页
                            if (diffY > 0) {
                                this.nextPage();
                            } else {
                                this.prevPage();
                            }
                        } else {
                            // PC端：向左滑动下一页，向右滑动上一页
                            if (diffX > 0) {
                                this.nextPage();
                            } else {
                                this.prevPage();
                            }
                        }
                    }
                    
                    // 延迟移除swiping类，确保动画完成
                    setTimeout(() => {
                        pageContainer.classList.remove('swiping');
                    }, 100);
                    
                    startX = 0;
                    startY = 0;
                    currentY = 0;
                    isDragging = false;
                });
            }
            
            showPage(pageIndex) {
                console.log('showPage called with pageIndex:', pageIndex);
                
                // 根据设备类型选择正确的容器
                const pageContainer = this.isMobile ? 
                    document.querySelector('.mobile-page-container') : 
                    document.querySelector('.page-container');
                
                const allPages = pageContainer ? pageContainer.querySelectorAll('.page') : document.querySelectorAll('.page');
                console.log('Found pages:', allPages.length);
                
                // 添加过渡类
                if (pageContainer) {
                    pageContainer.classList.add('swiping');
                }
                
                // 隐藏所有页面
                allPages.forEach((page, index) => {
                    page.classList.remove('active', 'prev', 'next');
                    console.log('Page ' + index + ':', page.id, page.classList.toString());
                });
                
                // 显示当前页面
                const currentPageEl = document.getElementById('page-' + pageIndex);
                console.log('Current page element:', currentPageEl);
                
                if (currentPageEl) {
                    // 添加淡入效果
                    currentPageEl.style.opacity = '0';
                    currentPageEl.classList.add('active');
                    
                    // 使用requestAnimationFrame确保样式应用
                    requestAnimationFrame(() => {
                        currentPageEl.style.opacity = '1';
                        console.log('Added active class to page:', currentPageEl.id);
                    });
                } else {
                    console.error('Page element not found:', 'page-' + pageIndex);
                }
                
                // 移除过渡类，恢复动画
                setTimeout(() => {
                    if (pageContainer) {
                        pageContainer.classList.remove('swiping');
                    }
                }, 50);
                
                // 更新导航
                this.updateNavigation();
            }
            
        }
        
        // 初始化多页面管理器
        new MultiPageManager();
    </script>
</body>
</html>`;
    }

    /**
     * 生成元素HTML
     * @param {Array} elements - 元素数组
     * @returns {string} 元素HTML字符串
     */
    generateElementsHTML(elements) {
        if (!elements || !Array.isArray(elements) || elements.length === 0) {
            return '';
        }

        return elements.map(element => {
            return this.generateElementHTML(element);
        }).join('\n        ');
    }

    /**
     * 生成单个元素HTML
     * @param {Object} element - 元素对象
     * @returns {string} 元素HTML字符串
     */
    generateElementHTML(element) {
        const { type, content, style, id, x, y, events } = element;
        
        // 转换样式对象为CSS字符串
        const styleStr = this.convertStyleToCSS(style);
        
        // 添加位置样式
        const positionStyle = `position: absolute; left: ${x}px; top: ${y}px;`;
        const fullStyle = `${positionStyle} ${styleStr}`;
        
        // 生成动画类
        let animationClasses = 'element';
        if (style.animationName && style.animationName !== 'none') {
            animationClasses += ` animate__animated animate__${style.animationName}`;
        }
        
        // 生成事件属性
        const eventAttrs = this.generateEventAttributes(events);
        
        // 根据元素类型生成HTML
        switch (type) {
            case 'text':
                return `<div id="${id}" class="${animationClasses}" style="${fullStyle}" ${eventAttrs}>${this.escapeHTML(content)}</div>`;
            
            case 'image':
                // 图片元素直接使用样式，border-radius已包含在fullStyle中
                return `<img id="${id}" class="${animationClasses}" src="${this.escapeHTML(content)}" style="${fullStyle}" alt="图片" ${eventAttrs} />`;
            
            case 'button':
                return `<button id="${id}" class="${animationClasses}" style="${fullStyle}" ${eventAttrs}>${this.escapeHTML(content)}</button>`;
            
            case 'input':
                return `<input id="${id}" class="${animationClasses}" type="text" placeholder="${this.escapeHTML(content)}" style="${fullStyle}" ${eventAttrs} />`;
            
            case 'grid':
                return this.generateGridHTML(element, fullStyle, animationClasses, eventAttrs);
            
            default:
                return `<div id="${id}" class="${animationClasses}" style="${fullStyle}" ${eventAttrs}>${this.escapeHTML(content)}</div>`;
        }
    }

    /**
     * 生成事件属性
     * @param {Object} events - 事件对象
     * @returns {string} 事件属性字符串
     */
    generateEventAttributes(events) {
        if (!events) return '';
        
        let attrs = '';
        
        // 点击事件
        if (events.click && events.click !== 'none') {
            switch (events.click) {
                case 'alert':
                    attrs += ` onclick="alert('元素被点击了！')"`;
                    break;
                case 'link':
                    if (events.clickLink) {
                        attrs += ` onclick="window.open('${this.escapeHTML(events.clickLink)}', '_blank')"`;
                    }
                    break;
                case 'custom':
                    if (events.clickCustom) {
                        attrs += ` onclick="${this.escapeHTML(events.clickCustom)}"`;
                    }
                    break;
            }
        }
        
        // 触摸事件
        if (events.touch && events.touch !== 'none') {
            switch (events.touch) {
                case 'alert':
                    attrs += ` ontouchstart="alert('元素被触摸了！')"`;
                    break;
                case 'link':
                    if (events.touchLink) {
                        attrs += ` ontouchstart="window.open('${this.escapeHTML(events.touchLink)}', '_blank')"`;
                    }
                    break;
                case 'custom':
                    if (events.touchCustom) {
                        attrs += ` ontouchstart="${this.escapeHTML(events.touchCustom)}"`;
                    }
                    break;
            }
        }
        
        // 悬停事件
        if (events.hover && events.hover !== 'none') {
            switch (events.hover) {
                case 'alert':
                    attrs += ` onmouseenter="alert('元素被悬停了！')"`;
                    break;
                case 'custom':
                    if (events.hoverCustom) {
                        attrs += ` onmouseenter="${this.escapeHTML(events.hoverCustom)}"`;
                    }
                    break;
            }
        }
        
        return attrs;
    }

    /**
     * 生成网格HTML
     * @param {Object} element - 网格元素对象
     * @param {string} fullStyle - 完整样式字符串
     * @param {string} animationClasses - 动画类字符串
     * @param {string} eventAttrs - 事件属性字符串
     * @returns {string} 网格HTML字符串
     */
    generateGridHTML(element, fullStyle, animationClasses, eventAttrs) {
        const { id, cols, content } = element;
        const gridContent = content || '';
        
        return `<div id="${id}" class="${animationClasses} grid-container" style="${fullStyle}" ${eventAttrs}>
            <div class="grid-header">${cols || 2}列网格</div>
            <div class="grid-content">
                ${gridContent}
            </div>
        </div>`;
    }

    /**
     * 生成背景样式
     * @param {Object} background - 背景对象
     * @returns {string} 背景样式字符串
     */
    generateBackgroundStyle(background) {
        if (!background) {
            return 'background: #ffffff;';
        }

        if (background.type === 'color') {
            return `background: ${background.color};`;
        } else if (background.type === 'image' && background.image) {
            return `background-image: url('${this.escapeHTML(background.image)}'); background-size: cover; background-position: center; background-repeat: no-repeat;`;
        }

        return 'background: #ffffff;';
    }

    /**
     * 生成页面容器样式
     * @param {Object} background - 背景对象
     * @returns {string} 页面容器样式字符串
     */
    generatePageContainerStyle(background) {
        const baseStyle = this.convertStyleToCSS(this.defaultStyles.pageContainer);
        const backgroundStyle = this.generateBackgroundStyle(background);
        
        return `${baseStyle} ${backgroundStyle}`;
    }

    /**
     * 生成完整的HTML文档
     * @param {Object} options - 选项对象
     * @returns {string} 完整HTML字符串
     */
    generateCompleteHTML(options) {
        const { elementsHTML, backgroundStyle, pageContainerStyle } = options;
        
        return `<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>H5页面预览</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css">
    <style>
        /* 全局样式重置 */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        html {
            font-size: 16px;
        }
        
        body {
            margin: 0;
            padding: 0;
            background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
            min-height: 100vh;
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
            display: flex;
            flex-direction: row;
            justify-content: center;
            padding: 20px;
            color: #333;
            gap: 30px;
        }
        
        /* 左侧手机区域 */
        .left-section {
            flex-shrink: 0;
        }
        
        /* 右侧信息区域 */
        .right-section {
            display: flex;
            flex-direction: column;
            gap: 20px;
            flex: 1;
            max-width: 400px;
        }
        
        /* 预览说明区域 */
        .preview-header {
            background: rgba(255, 255, 255, 0.9);
            backdrop-filter: blur(10px);
            border-radius: 16px;
            padding: 20px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
            border: 1px solid rgba(255, 255, 255, 0.3);
            text-align: left;
            width: 100%;
            flex-shrink: 0;
        }
        
        .preview-title {
            font-size: 22px;
            font-weight: 700;
            color: #2d3748;
            margin-bottom: 12px;
            background: linear-gradient(135deg, #4a5568, #2d3748);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
        }
        
        .preview-subtitle {
            font-size: 14px;
            color: #718096;
            margin-bottom: 16px;
        }
        
        .preview-info {
            display: flex;
            flex-direction: column;
            gap: 12px;
            font-size: 13px;
            color: #4a5568;
        }
        
        .info-item {
            display: flex;
            align-items: center;
            gap: 6px;
        }
        
        .info-icon {
            width: 16px;
            height: 16px;
            background: linear-gradient(135deg, #667eea, #764ba2);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 10px;
            font-weight: bold;
        }
        
        /* 技术信息模块 */
        .tech-info {
            background: rgba(255, 255, 255, 0.9);
            backdrop-filter: blur(10px);
            border-radius: 16px;
            padding: 20px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
            border: 1px solid rgba(255, 255, 255, 0.3);
            width: 100%;
        }
        
        .tech-title {
            font-size: 18px;
            font-weight: 600;
            color: #2d3748;
            margin-bottom: 16px;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .tech-list {
            display: flex;
            flex-direction: column;
            gap: 12px;
        }
        
        .tech-item {
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 8px 0;
            border-bottom: 1px solid rgba(0, 0, 0, 0.05);
        }
        
        .tech-item:last-child {
            border-bottom: none;
        }
        
        .tech-label {
            font-size: 13px;
            color: #4a5568;
            font-weight: 500;
            min-width: 80px;
        }
        
        .tech-value {
            font-size: 13px;
            color: #2d3748;
            font-weight: 600;
        }
        
        .tech-badge {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
            padding: 2px 8px;
            border-radius: 12px;
            font-size: 11px;
            font-weight: 500;
        }
        
        /* 手机模拟器容器 */
        /* 手机预览框样式 */
        .phone-frame {
            position: relative;
            background: #1a1a1a;
            border-radius: 30px;
            padding: 20px;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
            border: 6px solid #2d3748;
            flex-shrink: 0;
            width: fit-content;
        }
        
        /* 手机屏幕 */
        .phone-screen {
            background: #000;
            border-radius: 20px;
            padding: 2px;
            position: relative;
            overflow: hidden;
        }
        
        /* 手机状态栏 */
        .phone-status-bar {
            background: #000;
            height: 24px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0 16px;
            font-size: 12px;
            color: white;
            font-weight: 600;
        }
        
        .status-left {
            display: flex;
            align-items: center;
            gap: 4px;
        }
        
        .status-right {
            display: flex;
            align-items: center;
            gap: 4px;
        }
        
        .status-dot {
            width: 4px;
            height: 4px;
            background: white;
            border-radius: 50%;
        }
        
        .status-battery {
            width: 20px;
            height: 10px;
            border: 1px solid white;
            border-radius: 2px;
            position: relative;
        }
        
        .status-battery::after {
            content: '';
            position: absolute;
            right: -3px;
            top: 2px;
            width: 2px;
            height: 6px;
            background: white;
            border-radius: 0 1px 1px 0;
        }
        
        .status-battery::before {
            content: '';
            position: absolute;
            left: 1px;
            top: 1px;
            width: 14px;
            height: 8px;
            background: #4ade80;
            border-radius: 1px;
        }
        
        /* 页面容器 */
        .page-container {
            ${pageContainerStyle}
            background: #ffffff;
            position: relative;
            overflow: hidden;
        }
        
        /* 元素样式 */
        .element {
            ${this.convertStyleToCSS(this.defaultStyles.element)}
        }
        
        /* 网格样式 */
        .grid-container {
            display: grid;
            gap: 10px;
            padding: 15px;
        }
        
        .grid-header {
            font-size: 12px;
            color: #666;
            margin-bottom: 10px;
            text-align: center;
            font-weight: bold;
        }
        
        .grid-content {
            display: grid;
            gap: 10px;
            height: calc(100% - 30px);
        }
        
        .grid-item {
            background: white;
            border: 1px solid #ddd;
            border-radius: 4px;
            padding: 8px;
            min-height: 40px;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        /* 底部说明 */
        .preview-footer {
            margin-top: 16px;
            text-align: left;
            color: #718096;
            font-size: 12px;
            line-height: 1.5;
        }
        
        .footer-link {
            color: rgba(255, 255, 255, 0.9);
            text-decoration: none;
            font-weight: 500;
        }
        
        .footer-link:hover {
            color: white;
            text-decoration: underline;
        }
        
        /* 响应式设计 */
        @media (max-width: 768px) {
            body {
                padding: 0;
                flex-direction: column;
                gap: 0;
                background: #000;
            }
            
            .preview-header {
                display: none;
            }
            
            .phone-frame {
                border-radius: 0;
                padding: 0;
                box-shadow: none;
                border: none;
                width: 100%;
                height: 100vh;
            }
            
            .phone-screen {
                border-radius: 0;
                height: 100vh;
            }
            
            .phone-status-bar {
                display: none;
            }
            
            .page-container {
                height: 100vh;
                border-radius: 0;
            }
            
            .preview-footer {
                display: none;
            }
        }
    </style>
</head>
<body>
    <!-- 左侧手机模拟器 -->
    <div class="left-section">
        <div class="phone-container">
            <div class="phone-screen">
                <!-- 手机状态栏 -->
                <div class="phone-status-bar">
                    <div class="status-left">
                        <span>9:41</span>
                    </div>
                    <div class="status-right">
                        <div class="status-dot"></div>
                        <div class="status-dot"></div>
                        <div class="status-dot"></div>
                        <div class="status-battery"></div>
                    </div>
                </div>
                
                <!-- 页面内容 -->
                <div class="page-container">
                    ${elementsHTML}
                </div>
            </div>
        </div>
    </div>
    
    <!-- 右侧信息区域 -->
    <div class="right-section">
        <!-- 预览说明模块 -->
        <div class="preview-header">
            <h1 class="preview-title">📱 H5页面预览</h1>
            <p class="preview-subtitle">这是您的移动端页面在PC上的预览效果</p>
            <div class="preview-info">
                <div class="info-item">
                    <div class="info-icon">📐</div>
                    <span>设计尺寸: 375px × 667px</span>
                </div>
                <div class="info-item">
                    <div class="info-icon">📱</div>
                    <span>移动端适配</span>
                </div>
                <div class="info-item">
                    <div class="info-icon">⚡</div>
                    <span>实时预览</span>
                </div>
            </div>
        </div>
        
        <!-- 技术信息模块 -->
        <div class="tech-info">
            <h2 class="tech-title">🔧 技术规格</h2>
            <div class="tech-list">
                <div class="tech-item">
                    <span class="tech-label">框架</span>
                    <span class="tech-value">Koa.js + HTML5</span>
                </div>
                <div class="tech-item">
                    <span class="tech-label">响应式</span>
                    <span class="tech-badge">移动优先</span>
                </div>
                <div class="tech-item">
                    <span class="tech-label">单位</span>
                    <span class="tech-value">px (375px基准)</span>
                </div>
                <div class="tech-item">
                    <span class="tech-label">兼容性</span>
                    <span class="tech-value">iOS 12+ / Android 8+</span>
                </div>
                <div class="tech-item">
                    <span class="tech-label">生成时间</span>
                    <span class="tech-value">${new Date().toLocaleString('zh-CN')}</span>
                </div>
            </div>
        </div>
    </div>
</body>
</html>`;
    }

    /**
     * 将样式对象转换为CSS字符串
     * @param {Object} style - 样式对象
     * @returns {string} CSS字符串
     */
    convertStyleToCSS(style) {
        if (!style || typeof style !== 'object') {
            return '';
        }

        return Object.entries(style)
            .map(([key, value]) => {
                // 将驼峰命名转换为CSS属性名
                const cssKey = key.replace(/([A-Z])/g, '-$1').toLowerCase();
                return `${cssKey}: ${value}`;
            })
            .join('; ');
    }

    /**
     * HTML转义
     * @param {string} text - 要转义的文本
     * @returns {string} 转义后的文本
     */
    escapeHTML(text) {
        if (typeof text !== 'string') {
            return '';
        }

        // 在Node.js环境中使用字符串替换进行HTML转义
        return text
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#39;');
    }

    /**
     * 生成页面元数据
     * @param {Object} pageData - 页面数据
     * @returns {Object} 元数据对象
     */
    generateMetadata(pageData) {
        return {
            title: pageData.title || 'H5页面预览',
            description: pageData.description || '由H5页面构建器生成的预览页面',
            keywords: pageData.keywords || 'H5,移动端,页面构建器',
            author: pageData.author || 'H5页面构建器',
            viewport: 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no'
        };
    }

    /**
     * 验证页面数据
     * @param {Object} pageData - 页面数据
     * @returns {Object} 验证结果
     */
    validatePageData(pageData) {
        const errors = [];

        if (!pageData) {
            errors.push('页面数据不能为空');
            return { valid: false, errors };
        }

        // 检查是否是多页面数据
        if (pageData.pages && Array.isArray(pageData.pages)) {
            // 多页面数据验证
            if (pageData.pages.length === 0) {
                errors.push('至少需要一个页面');
            }

            pageData.pages.forEach((page, pageIndex) => {
                if (!page.elements || !Array.isArray(page.elements)) {
                    errors.push(`页面 ${pageIndex + 1} 的元素数据必须是数组`);
                } else {
                    page.elements.forEach((element, elementIndex) => {
                        if (!element.type) {
                            errors.push(`页面 ${pageIndex + 1} 的元素 ${elementIndex + 1} 缺少类型`);
                        }
                        if (typeof element.x !== 'number' || typeof element.y !== 'number') {
                            errors.push(`页面 ${pageIndex + 1} 的元素 ${elementIndex + 1} 位置数据无效`);
                        }
                    });
                }
            });
        } else {
            // 单页面数据验证（兼容旧版本）
            if (!Array.isArray(pageData.elements)) {
                errors.push('元素数据必须是数组');
            }

            if (pageData.elements) {
                pageData.elements.forEach((element, index) => {
                    if (!element.type) {
                        errors.push(`元素 ${index} 缺少类型`);
                    }
                    if (typeof element.x !== 'number' || typeof element.y !== 'number') {
                        errors.push(`元素 ${index} 位置数据无效`);
                    }
                });
            }
        }

        return {
            valid: errors.length === 0,
            errors
        };
    }
}

// 导出类（如果使用模块系统）
if (typeof module !== 'undefined' && module.exports) {
    module.exports = HtmlGenerator;
}
